package com.ttl.bc.ap.invoice.service;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import java.util.List;

import com.ttl.bc.ap.invoice.bean.BCAPInvoiceBean;

import com.ttl.bc.ap.invoice.bean.BCAPInvoiceSummary;
import com.ttl.bc.ap.invoice.bo.BCAPInvoiceDAO;

public class BCAPInvoiceService {
	
	@SuppressWarnings("unchecked")
	public BCAPInvoiceSummary getBCAPInvoice(String docNo) {
		
		//System.out.println("bcapinvoice service");
		BCAPInvoiceSummary bean = new BCAPInvoiceSummary();
		
		String hql = "FROM BCAPInvoiceBean " +
				"WHERE docNo='"+docNo+"' " +
						"or taxNo='"+docNo+"' " +
						"or billGroup='"+docNo+"' ";
		
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();				
		List result = dao.find(hql);		
		//System.out.println(result.size());
		
		if(result!=null && result.size()>0) {
			BCAPInvoiceBean i = (BCAPInvoiceBean)result.get(0); 
			bean.setDocNo(i.getDocNo());
			bean.setSumOfItemAmount(i.getSumOfItemAmount());
			bean.setTaxAmount(i.getTaxAmount());
			bean.setTotalAmount(i.getTotalAmount());
			bean.setNumOfItem(i.getBcAPInvoiceSubs().size());
			bean.setRemark2(i.getRemark2());
		}
		
		return bean;
	}
	
	@SuppressWarnings("unchecked")
	public BCAPInvoiceDocNoBean getMaxDocNo(String id) {

		BCAPInvoiceDocNoBean bean = new BCAPInvoiceDocNoBean();
		
		Date date = new Date();
		
		SimpleDateFormat simpleYear = new SimpleDateFormat("yyyy");
		String yearStr = simpleYear.format(date);
		
		if(Integer.valueOf(yearStr)<2500) {
			int yearStr2 = Integer.valueOf(yearStr)+543;
			yearStr = (""+yearStr2).substring(2);
		} else {
			yearStr = yearStr.substring(2);
		}
		
		SimpleDateFormat simpleMonth = new SimpleDateFormat("MM");
		@SuppressWarnings("unused")
		String monthStr = simpleMonth.format(date);
		
		String docNoStr = id;//+yearStr+monthStr;
		
		String hql = "SELECT MAX(docNo) FROM BCAPInvoiceBean WHERE docNo like '"+docNoStr+"%' ";

		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();				
		
		List result = dao.find(hql);
		String docNo = null;
		
		String maxDocNo = null;
		if(result.get(0) != null) {
			
			docNo = result.get(0).toString();
			int temp = 1+Integer.valueOf(docNo.substring(docNo.length()-4,docNo.length()));			
			NumberFormat formatter = new DecimalFormat("0000");
			docNo = formatter.format(temp);
			
			maxDocNo = docNoStr+"-"+docNo; 			
		}else {
			maxDocNo = docNoStr+"-0001";
		}
					
		bean.setDocNo(maxDocNo.substring(4, maxDocNo.length()));
		return bean;		
		
	}
}
